#!/bin/bash

#生成配置文件
function makeConf(){
 str="daemonize yes \n
port $2 \n
cluster-enabled yes \n
cluster-config-file nodes.conf \n
cluster-node-timeout 5000 \n
appendonly no";
 echo -e $str > "$1/redis.conf";
 echo $1;
}

#杀死所有的redis进程
ps -ef | grep redis | grep -v 'grep' | awk '{print $2}' | xargs kill -9

echo "请输入集群配置生成目录[注意:绝对路径]";
read path
if [ ! -n $path ]; then
   echo "目录不能为空";
   exit;
fi

#目录已经存在
if [ ! -d $path ];
then
    mkdir $path;
fi

echo "请输入端口开始值和端口个数空格隔开";
read port num;

host_str='';
i=1;
while (( $i<=$num ))
do
    dir=$path"/"`expr $port + $i`;
    if [ ! -d $dir ]
    then
        mkdir $dir;
    fi
    if [ ! -f "$dir/redis.conf" ]
    then
        makeConf $dir `expr $port + $i`;
        echo 22;
    fi
    rm -rf "$dir/nodes.conf";
    host_str="$host_str 127.0.0.1:"`expr $port + $i`;
    let "i++";
done

for conf in `ls $path`
do
   # 启动redis
    cd "$path/$conf";
    nohup /usr/bin/redis-server "$path/$conf/redis.conf" &
done

/usr/local/src/redis-3.2.1/src/redis-trib.rb create --replicas 1  $host_str


